package com.tencent.apps.ui.fragment;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.tencent.apps.R;
import com.tencent.apps.bean.AppInfo;
import com.tencent.apps.global.AppsApplication;
import com.tencent.apps.http.HttpHelper;
import com.tencent.apps.http.Url;
import com.tencent.apps.ui.adapter.AppsAdapter;
import com.tencent.apps.utils.CommonUtil;
import com.tencent.apps.utils.GsonUtil;
import com.tencent.apps.utils.LogUtil;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

public class AppFragment extends BaseFragment {


	private PullToRefreshListView refreshListView;
	private AppsAdapter adapter;
	private ListView listView;
	public ArrayList<AppInfo> list = new ArrayList<AppInfo>();;
	@Override
	protected Object requestData() {
		String json = HttpHelper.get(Url.HOME_APPS + list.size());//必须加list.size()，需要index的值。
		ArrayList<AppInfo>  appInfoList = (ArrayList<AppInfo>) GsonUtil.jsonToList(json,new TypeToken<List<AppInfo>>() {}.getType());
		LogUtil.d("###json2="+json);
		if (appInfoList != null) {
			list.addAll(appInfoList);
			CommonUtil.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					adapter.notifyDataSetChanged();
					refreshListView.onRefreshComplete();//完成刷新
				}
			});
		}
		return appInfoList;
	}

	@Override
	protected View getSuccessView() {
		initRefreshListView();
		
		adapter = new AppsAdapter(list, context);
		listView.setAdapter(adapter);
		
		return refreshListView;
	}

	public void initRefreshListView() {
		refreshListView = (PullToRefreshListView) View.inflate(context, R.layout.ptr_listview, null);
		refreshListView.setMode(Mode.BOTH);
		refreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			//刷新=下拉刷新+上拉加载更多，所以监听要判断是哪一种
			@Override
			public void onRefresh(final PullToRefreshBase<ListView> refreshView) {//final？？
				if (refreshListView.getMode() == Mode.PULL_FROM_START) {
					CommonUtil.runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							refreshView.onRefreshComplete();//完成刷新
						}
					});
				} else {
					contentPager.loadAndRefreshData();
				}
			}
		});
		
		listView = refreshListView.getRefreshableView();
		listView.setDividerHeight(0);
		listView.setSelector(android.R.color.transparent);
	}
}
